using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class JobSeekers_jobresult : System.Web.UI.Page
{
    string keyWord = "";
    string location = "";
    string category = "0";
    string industry = "0";
    string province = "0";

    string jobRange = "0";
    int itemPerPage = 15;
    int pagePerSeggment = 5;
    string postedJob = "0";
    string sortOrder = "JobTitle";
    string connectionString = "";
    
    protected void Page_Load(object sender, EventArgs e)
    {
        connectionString =
                 WebConfigurationManager.ConnectionStrings[
                   "RecruitVietnam"].ConnectionString;
        
        RegisterJavaScript(this.GridView1);
        Page searchPage = this.PreviousPage;
        RegisterJavaScript();
        if(searchPage != null)
        {
            switch (searchPage.Title)  
            {
                case "::Search for Jobs":
                    SearchCase(searchPage);
                    break;                 
                case "::RecruitVietnam":
                    HomeCase(searchPage); 
                    break;                 
                case "::My Account-Saved Search":
                    SavedSearchCase(searchPage);                                  
                    break;                 
            }
            ShowResult(keyWord, location, category,
            industry, province,  
            Convert.ToInt32(jobRange),
            Convert.ToInt32(postedJob), 0); 
            
            this.searchKeyword.Text = keyWord;
            this.workLocation.Text = location;
            this.jobCategory.SelectedValue = category;
            this.jobIndustry.Value = industry;
            this.jobProvince.Value = province;
            
            jobFrom.Value = jobRange;
            showMe.Value = itemPerPage.ToString();
            jobPosted.Value = postedJob;
            jobSort.Value = sortOrder;
                          
        }
        
        if (!IsPostBack)
        {
            ViewState["SortDirection"] = "ASC";
            LoadDataForDropDownList();
             
        }
        else
          CreateNavigation(Convert.ToInt32(
          literalPages.Text), Convert.ToInt32(
          literalCurrentPage.Text), itemPerPage,
          pagePerSeggment, this.panelNavigation);
             
    }
    void LoadDataForDropDownList()
    {
        Common cls = new Common(connectionString);
        DataTable dataTable = cls.GetDataTable(
        "select * from tblJobCategories");
        DropDownListHelper helper =
        new DropDownListHelper();
        helper.FillDataTableToDropDownList(
        dataTable, jobCategory,
       "JobCategoryName", "JobCategoryID",
        category);
    }
    void SavedSearchCase(Page searchPage)
    {
        GridView gridView = (GridView)
        searchPage.FindControl("GridView1");
        GridViewRow gridViewRow =
        gridView.Rows[Convert.ToInt32(
        Request.QueryString.Get("indexRow"))];

        keyWord = gridViewRow.Cells[2].Text;
        location = gridViewRow.Cells[3].Text;
        category = gridViewRow.Cells[4].Text;
        industry = gridViewRow.Cells[6].Text;
        province = gridViewRow.Cells[8].Text;

        if (location == "&nbsp;")
            location = "";
        jobRange = "0";

        postedJob = "0";
        sortOrder = "JobTitle";
   }
    void About(Page searchPage)
   {     
        TextBox textBox;
        DropDownList dropDownList;
        textBox = (TextBox)
        searchPage.FindControl("searchKeyword");
        keyWord = textBox.Text;
        textBox = (TextBox)
        searchPage.FindControl("workLocation");
        location = textBox.Text;
        dropDownList = (DropDownList)
        searchPage.FindControl("jobCategory");
        category = dropDownList.SelectedValue;
        dropDownList = (DropDownList)
        searchPage.FindControl("jobIndustry");
        industry = dropDownList.SelectedValue;
        dropDownList = (DropDownList)
        searchPage.FindControl("province");
        province = dropDownList.SelectedValue;

        jobRange = "0";

        postedJob = "0";
        sortOrder = "JobTitle";
    }
    void HomeCase(Page searchPage)
    {
        TextBox textBox;
        DropDownList dropDownList;
        textBox = (TextBox)
                    searchPage.FindControl("searchKeyword");
        keyWord = textBox.Text;
        textBox = (TextBox)
        searchPage.FindControl("workLocation");
        location = textBox.Text;
        dropDownList = (DropDownList)
        searchPage.FindControl("jobCategory");
        category = dropDownList.SelectedValue;
    }
    void SearchCase(Page searchPage)
    {
        TextBox textBox;
        DropDownList dropDownList;
        textBox = (TextBox)
        searchPage.FindControl("searchKeyword");
        keyWord = textBox.Text;
        textBox = (TextBox)
        searchPage.FindControl("workLocation");
        location = textBox.Text;
        dropDownList = (DropDownList)
        searchPage.FindControl("jobCategory");
        category = dropDownList.SelectedValue;

        dropDownList = (DropDownList)
        searchPage.FindControl("jobIndustry");
        industry = dropDownList.SelectedValue;
        dropDownList = (DropDownList)
        searchPage.FindControl("province");
        province = dropDownList.SelectedValue;


        dropDownList = (DropDownList)
        searchPage.FindControl("jobFrom");
        jobRange = dropDownList.SelectedValue;
        dropDownList = (DropDownList)
        searchPage.FindControl("showMe");
        itemPerPage = Convert.ToInt32(
        dropDownList.SelectedValue);
        dropDownList = (DropDownList)
        searchPage.FindControl("jobPosted");
        postedJob = dropDownList.SelectedValue;
        dropDownList = (DropDownList)
        searchPage.FindControl("jobSort");
        sortOrder = dropDownList.SelectedValue;
    }
     
    DataTable GetDataTable(string keyWord,
    string cityName, string jobCategory,
    string jobIndustry, string jobProvince,
    int viewable, int jobNoOfDate, 
    int firstRecord)
    {
        SqlServerProvider sqlServerProvider = 
        new SqlServerProvider();
        sqlServerProvider.ConnectionString = 
        connectionString;        
        sqlServerProvider.ParameterCollection 
        = new string[7] 
            {"@keyWord", "@workLocation", 
            "@jobCategory", "@jobIndustry", 
            "@jobProvince",
            "@viewable", "@jobNumberOfDate" };
        sqlServerProvider.ValueCollection = 
        new string[7] 
            { "%" + keyWord + "%", "%" + 
            location + "%", jobCategory, 
            jobIndustry, jobProvince, viewable.ToString(), 
            jobNoOfDate.ToString() };
        sqlServerProvider.CommandType = 
        CommandType.StoredProcedure;
                
        if (firstRecord == 0)
        {
            sqlServerProvider.CommandText = 
            "SPTotalSearchJob";
            literalTotal.Text =  
            sqlServerProvider.ExecuteScalar().ToString();
            ShowTotalPages(Convert.ToInt32(
            literalTotal.Text));
        }
        
        
        sqlServerProvider.CommandText = 
        "SPSearchJob";
        DataTable dataTable =  
        sqlServerProvider.GetDataTable(
        firstRecord *itemPerPage, itemPerPage);
        return dataTable;
    }

    void ShowTotalPages(int totalRecords)
    {
         
        int totalPages = totalRecords / itemPerPage;
        if (totalRecords % itemPerPage != 0)
            totalPages++;
        literalPages.Text = totalPages.ToString();
    }
    
    void CreateNavigation(  
    int totalPages, 
    int currentPage, 
    int itemPerPage, 
    int pagePerSeggent, 
    Panel panelLinks)
    {
        panelLinks.Controls.Clear();
        int startPageNo = 0; 
        int endPageNo = 0; 
        int seggmentNo = 0;
        if (totalPages > 1)
        {
            seggmentNo = 
            currentPage / pagePerSeggent;
            if ((currentPage % pagePerSeggent) > 0) 
                seggmentNo += 1;
            startPageNo = 
            pagePerSeggent*(seggmentNo -1) + 1;
            if (seggmentNo * pagePerSeggent > totalPages) 
                endPageNo = totalPages;
            else
                endPageNo = seggmentNo * pagePerSeggent;
             
            
            LinkButton linkButton;
            Label labelSpace;

            if (seggmentNo > 1)
            {
                linkButton = new LinkButton();
                linkButton.Text = "First";
                linkButton.Click += new 
                EventHandler(linkButton_Click);
                linkButton.ID = (1).ToString();
                labelSpace = new Label();
                labelSpace.Text = "&nbsp; ";
                panelLinks.Controls.Add(linkButton);
                panelLinks.Controls.Add(labelSpace);
            }
            
            if (currentPage > pagePerSeggent)
            {                        
                linkButton = new LinkButton();
                linkButton.Text = "Previous";
                linkButton.Click += new 
                EventHandler(linkButton_Click);
                linkButton.ID = (startPageNo-1).ToString();
                labelSpace = new Label();
                labelSpace.Text = "&nbsp; ";
                panelLinks.Controls.Add(linkButton);
                panelLinks.Controls.Add(labelSpace);
            }
            int i = 0;
            for (i = startPageNo; i <= endPageNo; i++)
            {
                linkButton = new LinkButton();
                linkButton.Text = i.ToString();
                
                linkButton.ID = i.ToString();
                if(i == currentPage)
                    linkButton.BackColor = 
                    System.Drawing.Color.Aqua;
                linkButton.Click += new 
                EventHandler(linkButton_Click);
                labelSpace = new Label();
                labelSpace.Text = "&nbsp; ";
                panelLinks.Controls.Add(linkButton);
                panelLinks.Controls.Add(labelSpace);
            }
            if (seggmentNo * pagePerSeggent < totalPages) 
            {
                linkButton = new LinkButton();
                linkButton.Text = "Next";  
                linkButton.ID = (i).ToString();
                linkButton.Click += new 
                EventHandler(linkButton_Click);
                labelSpace = new Label();
                labelSpace.Text = "&nbsp; ";
                panelLinks.Controls.Add(linkButton);
                panelLinks.Controls.Add(labelSpace);
            }
            if (seggmentNo * pagePerSeggent +1< totalPages)
            {
                linkButton = new LinkButton();
                linkButton.Text = "Last";
                linkButton.ID = totalPages.ToString();
                linkButton.Click += new 
                EventHandler(linkButton_Click);
                labelSpace = new Label();
                labelSpace.Text = "&nbsp;";
                panelLinks.Controls.Add(linkButton);
                panelLinks.Controls.Add(labelSpace);
            }
        }
    }
    
    void linkButton_Click(object sender, EventArgs e)
    {
        
        keyWord = searchKeyword.Text;
        location = workLocation.Text;
        category = this.jobCategory.SelectedValue;
        industry = this.jobIndustry.Value;
        province = this.jobProvince.Value;

        jobRange = jobFrom.Value;
        itemPerPage = 
        Convert.ToInt32(showMe.Value);
        postedJob = jobPosted.Value;
        sortOrder = jobSort.Value;
        
        LinkButton linkButton = 
        (LinkButton)sender;
        
        int nextPage = 0;         
        nextPage =  Convert.ToInt32(linkButton.ID);
        literalCurrentPage.Text = 
        nextPage.ToString();
        int endJobs = 
        nextPage * Convert.ToInt32(itemPerPage);
        if (endJobs > Convert.ToInt32(literalTotal.Text)) 
            endJobs = Convert.ToInt32(literalTotal.Text);
        literalRecords.Text = 
        " - Display job: " + 
        (nextPage - 1) *  itemPerPage  + 
        " -> " + endJobs.ToString();
        
        ShowResult(keyWord, location, category,
            industry, province,  
            Convert.ToInt32(jobRange),
            Convert.ToInt32(postedJob), 
            nextPage -1);

         
    }
    DataView GetDataView(string keyWord,
    string cityName, string jobCategory,
    string jobIndustry, string jobProvince,
    int viewable, int jobNoOfDate,
    string columnName, string sortType, int firstRecord)
    {
        SqlServerProvider sqlServerProvider = 
        new SqlServerProvider();
        sqlServerProvider.ConnectionString = 
        connectionString;
        
        sqlServerProvider.ParameterCollection 
        = new string[7] 
            { "@keyWord", "@workLocation", 
            "@jobCategory", "@jobIndustry", 
            "@jobProvince",
            "@viewable", "@jobNumberOfDate" };
        sqlServerProvider.ValueCollection 
        = new string[7] 
            { "%" + keyWord + "%", "%" + 
            location + "%", jobCategory, 
            jobIndustry, jobProvince, 
            viewable.ToString(), 
            jobNoOfDate.ToString() };
        sqlServerProvider.CommandType = 
        CommandType.StoredProcedure;
         
        sqlServerProvider.CommandText = 
        "SPSearchJob";
        DataTable dataTable = 
        sqlServerProvider.GetDataTable(
        firstRecord * itemPerPage, itemPerPage);
        DataView dataView = new DataView(dataTable);
        dataView.Sort = columnName + " " + sortType;
        return dataView;
    } 
    void ShowResult(string keyWord,
    string cityName, string jobCategory,
    string jobIndustry, 
    string jobProvince,
    int viewable, int jobNoOfDate, 
    int firstRecord)
    {
        try
        {
            
            GridViewHelper gridViewHelper = 
            new GridViewHelper();
            gridViewHelper.FillDataTableToGridView(
            GetDataTable(keyWord, cityName, 
            jobCategory, jobIndustry, jobProvince,
            viewable, jobNoOfDate, firstRecord),
            this.GridView1);
            if (GridView1.Rows.Count == 0)
                {
                    litError.Text = "Job not found.";
                    ShowHide(false);
                }
            else
                {
                    ShowHide(true);
                int currentRecords =  
                Convert.ToInt32(literalCurrentPage.Text);  
                litError.Text = "";
                literalRecords.Text = 
                " - Display job: " +
                ((currentRecords - 1) * itemPerPage + 1).ToString()
                + "-" ;
                if ((currentRecords - 1) * itemPerPage + 
                itemPerPage < Convert.ToInt32(literalTotal.Text))
                    literalRecords.Text +=
                    ((currentRecords - 1) * itemPerPage + 
                    itemPerPage).ToString();
                else
                    literalRecords.Text += literalTotal.Text;
                literalRecords.Text+= " of " + 
                literalTotal.Text ;
            }
            CreateNavigation(Convert.ToInt32(
                         literalPages.Text), Convert.ToInt32(
                         literalCurrentPage.Text), itemPerPage,
                         pagePerSeggment, this.panelNavigation);   
        }
        catch(Exception ex)
        {
            litError.Text = ex.Message;
        }
    }
    void ShowHide(bool flag)
    {
        literalTotal.Visible = flag;
        literalCurrentPage.Visible = flag;
        literalOfText.Visible = flag;
        literalPageText.Visible = flag;
        literalTotalText.Visible = flag;
        literalRecords.Visible = flag;
        literalPages.Visible = flag;
    }
    
    void ShowResult(string keyWord,
    string cityName, string jobCategory,
    string jobIndustry, 
    string jobProvince, 
    int viewable, int jobNoOfDate,
    string columnName, string sortType, 
    int firstRecord)
    {
        try
        {
            GridViewHelper gridViewHelper = 
            new GridViewHelper();
            gridViewHelper.FillDataViewToGridView(
            GetDataView(keyWord, cityName, 
            jobCategory, jobIndustry, 
            jobProvince, viewable,
            jobNoOfDate, columnName, 
            sortType, firstRecord),
            this.GridView1);
            if (GridView1.Rows.Count == 0)
                litError.Text = "Job not found.";
            else
                litError.Text = "";
        }
        catch (Exception ex)
        {
            litError.Text = ex.Message;
        }
    }
    void RegisterJavaScript()
    {
        string javaScript = 
        "<script langugage=javascript> "+
        "function NewSearch(){";
        javaScript += "window.open(\"" +
        " search.aspx\", target='_main');} "+
        "</script>";        
        ClientScript.RegisterClientScriptBlock(
        this.GetType(), "JobResult", javaScript);
    }

    void RegisterJavaScript(GridView GridView1)
    {
        Common common = new Common();
        ClientScript.RegisterClientScriptBlock(
        this.GetType(), "openWindow" +
        GridView1.ID,
        common.CreateScriptForPrint(
        GridView1.ID));
        btnPrint.Attributes.Add("onclick",
        "openWindow" + GridView1.ID +
        "('" + GridView1.ID.ToString() +
        "',400,700);return false;");
    }
 
    protected void btnSearch_Click(
    object sender, EventArgs e)
    {                
        keyWord = searchKeyword.Text;
        location = workLocation.Text;
        category = this.jobCategory.SelectedValue;
        industry = this.jobIndustry.Value;
        province = this.jobProvince.Value;
        
        jobRange = jobFrom.Value;
        itemPerPage = Convert.ToInt32(showMe.Value);
        postedJob = jobPosted.Value;
        sortOrder = jobSort.Value;

        literalCurrentPage.Text = "1";
        
       
        
        ShowResult(keyWord, location, category,
             industry, province,  
             Convert.ToInt32(jobRange),
             Convert.ToInt32(postedJob), 0);
         
          
    }
    protected void btnSaveJobSearch_Click(
    object sender, EventArgs e)
    {
        if (Convert.ToString(
            Session["jsuserid"]) == "")
            Response.Redirect("login.aspx");
        keyWord = searchKeyword.Text;
        location = workLocation.Text;
        category = this.jobCategory.SelectedValue;
        industry = this.jobIndustry.Value;
        RecruitVietnam recruitVietnam
        = new RecruitVietnam();
        recruitVietnam.ConnectionString 
        = connectionString;
        recruitVietnam.SaveJobSearch(
        Convert.ToString(Session["jsuserid"]), 
        keyWord, location, category, industry);
    }

    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
         
        keyWord = searchKeyword.Text;
        location = workLocation.Text;
        category = this.jobCategory.SelectedValue;
        industry = this.jobIndustry.Value;
        province = this.jobProvince.Value;

        jobRange = jobFrom.Value;
        itemPerPage = Convert.ToInt32(showMe.Value);
        postedJob = jobPosted.Value;
        sortOrder = jobSort.Value;
        ShowResult(keyWord, location, category,
        industry, province,  
        Convert.ToInt32(jobRange),
        Convert.ToInt32(postedJob), 
        e.SortExpression, 
        ViewState["SortDirection"].ToString(), 
        Convert.ToInt32(literalCurrentPage.Text)-1);
        
        if (ViewState["SortDirection"].ToString() == "ASC")
            ViewState["SortDirection"] = "DESC";
        else
            ViewState["SortDirection"] = "ASC";
                   
    }
     
}
